package com.minisoft.pms;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ReflectUtil;
import lombok.Data;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Data
public class WorkflowRequestVO {
    private String saplcbh; // 集成系统审批编号
    private String saplclx = "PMS"; // 集成系统流程审批类型
    private String requestId; // 流程ID,为空时为创建，不为空时更新对应的流程
    private String creatorId; // 创建人
    private String isNext = "0"; // 是否提交下一节点,0不提交，1提交
    private String requestName; // 流程标题
    private String workflowId; // 流程类型ID
    private Object workflowMainTableInfo; // 主表数据
    private List<Object> workflowDetailTableInfos1; // 明细表数据1
    private List<Object> workflowDetailTableInfos2; // 明细表数据2

    @Data
    public static class Attachment {
        private List<String> names = new ArrayList<>(); // 附件名称
        private List<String> urls = new ArrayList<>(); // 附件路径
        public void add(String name, String url) {
            this.names.add(name);
            this.urls.add(url);
        }
        // 返回格式为 http:file1|http:file2 的名称字符串
        public String getNames() {
            return names.stream().map(item -> "http:" + item).collect(Collectors.joining("|"));
        }

        // 返回 URL 字符串，用 | 分隔
        public String getUrls() {
            return String.join("|", urls);
        }
    }
    public String toXmlString() {
        StringBuilder xmlBuilder = new StringBuilder();
        xmlBuilder.append("<workflowRequestInfo>");

        // 添加基本字段
        xmlBuilder.append("<saplcbh>").append(saplcbh).append("</saplcbh>");
        xmlBuilder.append("<saplclx>").append(saplclx).append("</saplclx>");
        xmlBuilder.append("<creatorId>").append(creatorId).append("</creatorId>");
        xmlBuilder.append("<isNext>").append(isNext).append("</isNext>");
        xmlBuilder.append("<requestName>").append(requestName).append("</requestName>");
        xmlBuilder.append("<workflowId>").append(workflowId).append("</workflowId>");

        // 添加主表数据
        if (workflowMainTableInfo != null) {
            xmlBuilder.append("<workflowMainTableInfo>");
            appendObjectFields(xmlBuilder, workflowMainTableInfo);
            xmlBuilder.append("</workflowMainTableInfo>");
        }

        if (CollUtil.isNotEmpty(workflowDetailTableInfos1) || CollUtil.isNotEmpty(workflowDetailTableInfos2)) {
            // 添加明细表数据
            xmlBuilder.append("<workflowDetailTableInfos>");
            int startId = addDetailTableInfo(xmlBuilder, workflowDetailTableInfos1, 0);// 从 id=0 开始
            addDetailTableInfo(xmlBuilder, workflowDetailTableInfos2, startId); // 继续 id
            xmlBuilder.append("</workflowDetailTableInfos>");
        }

        xmlBuilder.append("</workflowRequestInfo>");
        return xmlBuilder.toString();
    }

    private int addDetailTableInfo(StringBuilder xmlBuilder, List<Object> workflowDetailTableInfos, int startId) {
        if (workflowDetailTableInfos != null && !workflowDetailTableInfos.isEmpty()) {
            xmlBuilder.append("<workflowDetailTable>");
            xmlBuilder.append("<id>").append(startId).append("</id>"); // 动态生成 id
            for (int i = 0; i < workflowDetailTableInfos.size(); i++) {
                Object detailTable = workflowDetailTableInfos.get(i);
                xmlBuilder.append("<workflowRequestTableRecords>");
                appendObjectFields(xmlBuilder, detailTable);
                xmlBuilder.append("</workflowRequestTableRecords>");
            }
            xmlBuilder.append("</workflowDetailTable>");
            startId++;
        }
        return startId;
    }

    /**
     * 将对象的属性动态转换为 XML 字段
     */
    private void appendObjectFields(StringBuilder xmlBuilder, Object obj) {
        if (obj == null) return;
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            Object fieldValue = ReflectUtil.getFieldValue(obj,field);
            if (fieldValue != null) {
                appendField(xmlBuilder, field.getName(), fieldValue);
            }
        }
    }

    /**
     * 添加单个字段到 XML
     */
    private void appendField(StringBuilder xmlBuilder, String fieldName, Object fieldValue) {
        xmlBuilder.append("<workflowRequestTableField>");
        //如果是附件，则需要特殊处理
        if (fieldValue instanceof Attachment) {
            Attachment attachment = (Attachment) fieldValue;
            String fieldType = attachment.getNames();
            fieldValue = attachment.getUrls();
            xmlBuilder.append("<fieldType>").append(fieldType).append("</fieldType>");
        }
        xmlBuilder.append("<fieldName>").append(fieldName).append("</fieldName>")
                .append("<fieldValue>").append(fieldValue).append("</fieldValue>")
                .append("</workflowRequestTableField>");
    }

    public static void main(String[] args) {
        WorkflowRequestVO requestVO = new WorkflowRequestVO();
        requestVO.setSaplcbh("f519215dc52a434dbd7899f62dcbcb90");
        requestVO.setCreatorId("linshuying");
        requestVO.setRequestName("华发数智项目变更审批表");
        requestVO.setWorkflowId("22442");

        // 设置主表数据
        MainTable mainTable = new MainTable();
        mainTable.setRequestType("3");
        mainTable.setRequestName("2");
        mainTable.setRequestId("1");
        Attachment fj = new Attachment();
        fj.add("文件名称1","http://XXXXXXXX1");
        fj.add("文件名称2","http://XXXXXXXX2");
        mainTable.setFj(fj);
        requestVO.setWorkflowMainTableInfo(mainTable);

        // 设置明细表数据1
        DetailTable detailTable1 = new DetailTable();
        detailTable1.setSqr("linshuying");
        detailTable1.setCe("测试");
        DetailTable detailTable3 = new DetailTable();
        detailTable3.setSqr("linshuying");
        detailTable3.setCe("测试");
        requestVO.setWorkflowDetailTableInfos1(ListUtil.of(detailTable1,detailTable3));

        // 设置明细表数据2
        DetailTable detailTable2 = new DetailTable();
        detailTable2.setFenb("0706");
        detailTable2.setBum("0817");
        requestVO.setWorkflowDetailTableInfos2(ListUtil.of(detailTable2));

        String xmlString = requestVO.toXmlString();
        System.out.println(xmlString);
    }

    // 主表数据类（测试用）
    @Data
    public static class MainTable {
        private String requestType;
        private String requestName;
        private String requestId;
        private Attachment fj; // 文件字段
    }

    // 明细表数据类（测试用）
    @Data
    public static class DetailTable {
        private String sqr;
        private String ce;
        private String fenb;
        private String bum;
    }
}